﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

/// <summary>
/// Summary description for FundPrice
/// </summary>
public class FundPrice
{
	public FundPrice()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public string fundCode { set; get; }
    public DateTime valuationDate { set; get; }
    public decimal bidPrice { set; get; }
    public decimal offerPrice { set; get; }
    public string currency { set; get; }
    
    public void save()
    {
        SqlConnection conn = DBManager.getSqlConnection();
        conn.Open();

        string sql = "insert into R_FUND_DAILY_PRICE (fund_code, valuation_date, bid_price, offer_price,currency) values (@f,@v,@b,@o,@c)";
        var cmd = new SqlCommand(sql, conn);

        cmd.Parameters.Add(new SqlParameter("@f", (object)fundCode ?? DBNull.Value));
        cmd.Parameters.Add(new SqlParameter("@v", (object)valuationDate ?? DBNull.Value));
        cmd.Parameters.Add(new SqlParameter("@b", (object)bidPrice ?? DBNull.Value));
        cmd.Parameters.Add(new SqlParameter("@o", (object)offerPrice ?? DBNull.Value));
        cmd.Parameters.Add(new SqlParameter("@c", (object)currency ?? DBNull.Value));

        cmd.ExecuteNonQuery();
        conn.Close();
    }

    public static FundPrice getLastPrice(string fundCode)
    {

        SqlConnection conn = DBManager.getSqlConnection();
        conn.Open();

        string sql = "SELECT top 1 * FROM R_FUND_DAILY_PRICE D  WHERE D.fund_code=@fundCode ORDER BY valuation_date desc";

        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.Parameters.Add(new SqlParameter("@fundCode", (object)fundCode ?? DBNull.Value));

        SqlDataReader dr = cmd.ExecuteReader();
        FundPrice price = new FundPrice();


        if (dr.Read())
        {
            price.valuationDate = dr.GetDateTime(2);
            price.bidPrice = dr.GetDecimal(3);
            price.offerPrice = dr.GetDecimal(4);

        }

        dr.Close();
        conn.Close();

        return price;


    }

}